<?php

namespace App\Helpers;

use App\Model\Article;
use App\Model\Resource;
use App\Model\UserPoster;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;

class ArticlePoster
{
    public function create($product_id,$user_id,$username="丁花花绘本")
    {

        $product = Article::find($product_id);

        if (!$product) return false;

        $posterPath  = false;

        if (!$product->poster || $product->poster && strtotime($product->poster_create) >time()+3600*10){
            $posterPath = $this->createPost($product);
            $product->poster = $posterPath;
            $product->poster_create = date('Y-m-d H:i:s');
            $product->save();

        }

        if ($username){

            //没有则重新生成
            $up = new UserPoster();
            $up->obj_id = $product_id;
            $up->user_id = $user_id;
            $up->username = $username;
            $up->path = '';
            $up->type = 'article';
            $up->save();

            //如果更新了底图则更新海报
            if ($posterPath) {
                $posterPath = $this->addPosterUser($posterPath,$up->id,$username,$product->id);
                $up->path = $posterPath;
                $up->save();
                return $posterPath;
            }

            //查找用户生成的用户海报
            $item = DB::table('t_user_poster')->where('obj_id','=',$product_id)->where('user_id','=',$user_id)
                ->where('username','=',$username)
                ->where('type','=','article')
                ->whereNotNull('path')
                ->where('created_at','<',date('Y-m-d H:i:s',time()+21600))
                ->orderBy('created_at','desc')
                ->first();

            if ($item && $item->path) return $item->path;

            if($posterPath = $this->addPosterUser($product->poster,$up->id,$username,$product->id)){
                $up->path = $posterPath;
                $up->save();
                return $posterPath;
            }
        }
        return $posterPath;
    }

    public function createPost($product)
    {

        $root = storage_path('app/public/canvas/');
        @mkdir($root);
        $template_path = storage_path('app/template/');
        $filename = md5(time().str_random(32)).'.jpg';
        @mkdir(storage_path('app/public/poster'));

        $savePath = storage_path('app/public/poster/').$filename;

        $font_path = $template_path.'PingFang Regular.ttf';

        $manager =  new ImageManager(['driver' => 'imagick']);
        $img = $manager->make(storage_path('app/template/backgroud_article_1.jpg'))->resize(750,1334);

        //封面图片
        $cover  = $product->covers()->first();
        if ($cover && $cover->imgSrv){
            $cover = $manager->make($cover->imgSrv);
            $w = $cover->getWidth()*637/$cover->getHeight();
            $cover = $cover->resize(intval($w),637);
            $nw  = $cover->getWidth();
            $lw = intval(-0.5*($nw-750));
            $img->insert($cover,'top-left',$lw,0);
        }

        //标题
        if($product->title){
            $l = mb_strlen($product->title);
            $text[] = mb_substr($product->title,0,12);
            if ($l>12) $text[] = mb_substr($product->title,12,8);
            if ($l>24) $text[1] .= '...';

            foreach ($text as $k=>$v){
                $img->text($v,57,721+$k*83,function ($font) use ($font_path) {
                    $font->file($font_path);
                    $font->size(48);
                    $font->valign('bottom');
                    $font->color('#303030');
                });
            }
        }

        if ($product->content) {
            $replace = ["&nbsp;\n"=>"","\n\n"=>"","\n"=>"，","&nbsp;"=>"","&ldquo;"=>"","&rdquo;"=>"","&mdash;"=>""];
            $content = strtr(mb_substr(strip_tags($product->content),0,200),$replace);

            $content = preg_replace('/(，){2,}/','，',$content);

            if(mb_strpos('，',$content) == 0) $content = mb_substr($content,1);

            $cl = mb_strlen($content);
            $sub=0;
            $text = [];
            $i=0;
            while ($sub<$cl){
                $s = 26;
                $t = mb_substr($content,$sub,$s);
                if (preg_match('/.*?([A-Za-z]{0,}[A-Za-z]$)/',$t,$a)){
                    $al = mb_strlen($a[1]);
                    preg_match('/([A-Za-z]{1,})/i',mb_substr($content,$sub,$s*2),$a2);
                    $a2l = mb_strlen($a2[1]);
                    if ($al*2>=$a2l) {
                        $s += $a2l-$al;
                    }else{
                        $s = mb_strpos($t,$a[1]);
                    }
                    $t = mb_substr($content,$sub,$s);
                }
                if (preg_match('/([A-Za-z]{1,})![A-Za-z]$/i',$t,$as)){
                    $es = ceil(mb_strlen($as[1]) / 2) + 1;
                    $s += $es;
                    $t = mb_substr($content,$sub,$s);
                }
                $sub +=$s;
                $text[$i] = $t;
                if ($i>=2){
                    if (mb_strlen($t)>24){
                        $text[$i] = mb_substr($text[$i],0,24) . '...';
                    }
                    break;
                }
                $i++;
            }

            foreach ($text as $k=>$v){
                $img->text($v,57,880+$k*43,function ($font) use ($font_path) {
                    $font->file($font_path);
                    $font->size(24);
                    $font->valign('bottom');
                    $font->color('#808080');
                });
            }

        }

        $img->save($savePath,100);

        $disk = Storage::disk('qiniu');
        $qiniu_path = 'letsDrink/poster/product/'.date('Ymd') .'/'.$filename;
        $disk->put($qiniu_path,file_get_contents($savePath));
        unlink($savePath);
        return Resource::getQiniuSrv($qiniu_path);
    }

    public function addPosterUser($path,$userPosterId,$username,$productId)
    {
        $root = storage_path('app/public/poster');
        $date = date('Ymd');
        @mkdir($root);
        $root = $root.'/article';
        @mkdir($root);
        $root = $root.'/'.$date;
        @mkdir($root);

        $template_path = storage_path('app/template/');
        $filename = md5(time().str_random(32)).'.jpg';
        $savePath = $root.'/'.$filename;
        $outputPath = env('POSTER','https://api.letsdrink.com.cn/v2').'/storage/poster/article/'.$date.'/'.$filename;

        $font_path = $template_path.'PingFang Regular.ttf';

        $manager =  new ImageManager(['driver' => 'imagick']);
        $img = $manager->make($path)->resize(750,1334);
        $img->text('@'.$username.' 正在读这篇文章',60,1101,function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('bottom');
            $font->color('#7e7e7e');
        });

        //小程序码
        $miniProgram  = app('wechat.mini_program');
        $codePath = $miniProgram->app_code->getUnlimit($userPosterId)->saveAs(storage_path('app/public/xcx'),md5(time().str_random(32)).'.jpg');
        $codePath = storage_path('app/public/xcx/'.$codePath);
        $cover = $manager->make($codePath)->resize(120,120);
        $img->insert($cover,'top-left',58,1175);

        $img->save($savePath,100);
        unlink($codePath);

        if (file_exists($savePath)) {
            return $outputPath;
        }else{
            return false;
        }
    }

}
